/**
 * @Author 韦建韩
 * @Date 2022/5/16
 */
package com.example.devops.Manage;

import com.example.devops.CustomEnum.PublishState;
import com.example.devops.Manage.UserManager.UserInfoManage;
import com.example.devops.dao.MirrorCreateMapper;
import com.example.devops.dao.ProjectMapper;
import com.example.devops.dao.UserMapper;
import com.example.devops.entity.pojo.MirrorInformation;
import com.example.devops.entity.pojo.User;
import com.example.devops.exception.ValidationException;
import com.example.devops.service.IProjectService;
import com.example.devops.web.controller.applicationAdmin.ProjectPublishProcessServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Objects;

@Service
public class ProjectPublishCenter {
    Logger logger = LoggerFactory.getLogger(ProjectPublishCenter.class);
    @Autowired
    MirrorCreateMapper mirrorCreateMapper;
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    IProjectService projectService;


    private MirrorInformation getMirrorById(String mirrorId){
        MirrorInformation mirrorInformation = mirrorCreateMapper.selectById(Long.valueOf(mirrorId));
        if(Objects.isNull(mirrorInformation)){
            throw new ValidationException("镜像信息不存在");
        }
        return mirrorInformation;
    }

    public void run(String mirrorId, String userId, String branch) throws IOException {
        User user = userMapper.selectById(Long.valueOf(userId));
        UserInfoManage.set(user);
        logger.info("get getMirrorById,mirrorId{}, userId{}",mirrorId,userId);
        MirrorInformation mirrorById = getMirrorById(mirrorId);

        String port = HttpPortCache.getPort();
        if(Objects.isNull(port)){
            closeSession(mirrorId);
        }
        String gitAddr = mirrorById.getGitAddr();
        ProjectPublishManage manage = new ProjectPublishManage(userId, gitAddr, branch, port, mirrorId);
        long startTime = System.currentTimeMillis();
        try {
            logger.info("start publish,userId:{},gitAddr:{},branch:{},port:{},mirrorId:{}",userId,gitAddr,branch,port,mirrorId);
            manage.publish();
            logger.info("script success");
            //记录发布成功的项目
            projectService.insertSuccessProject(branch, mirrorId,port, mirrorById);
            //处理最近发布项目缓存
            RecentlyPublishCache.Entity entity = new RecentlyPublishCache.Entity();
            entity.setId(Long.parseLong(mirrorId));
            entity.setName(mirrorById.getName());
            entity.setUserId(Long.valueOf(userId));
            LinkedList<RecentlyPublishCache.Entity> linkList = RecentlyPublishCache.get();
            if(linkList.size() == 6){
                linkList.removeFirst();
            }
            boolean isExist = false;
            for (RecentlyPublishCache.Entity entity1 : linkList) {
                if (entity1.getId() == Long.parseLong(mirrorId)){
                    isExist = true;
                }
            }
            if(!isExist){
                linkList.addLast(entity);

            }
            ProjectPublishProcessServer.close(mirrorId, PublishState.SUCCESS.state);
        }catch (Exception e){
            long endTime = System.currentTimeMillis();
            logger.error("publish error,cost:{}",startTime-endTime,e);
            ProjectPublishProcessServer.close(mirrorId, PublishState.FAIL.state);
        }

    }
    private void closeSession(String mirrorId) throws IOException {
        ProjectPublishProcessServer.close(mirrorId, PublishState.FAIL.state);
    }
}
